package it.uniroma2.sd.db;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.Vector;

/*This class is used by the Table.class*/

//a map representing the columns of a row
//Columns are accessed by their name
//the value in the map is a list of columns representing the history of that column (the first element is the newest. [descending order])
public class ColumnsGroup implements IColumnsGroup
{
    /**
     * 
     */
    private static final long serialVersionUID = 470330294976603336L;
    private TreeMap<String, LinkedList<IColumn>> columnstreemap;

    public ColumnsGroup()
    {
	this.columnstreemap = new TreeMap<String, LinkedList<IColumn>>();
    }

    @Override
    public int size()
    {
	return this.columnstreemap.size();
    }

    /**
     * @Override If the columnkey of IColumn already exists in the ColumnsGroup, the new column updates the relative entry otherwise a new entry is created
     */
    @Override
    public void addColumn(IColumn column)
    {
	LinkedList<IColumn> entry_list;
	if ((entry_list = this.columnstreemap.get(column.getName())) != null)
	{
	    this.addFresherColumn(column, entry_list);
	}
	else
	{
	    this.createListAndAddColumn(column);
	}
    }

    @Override
    public IColumn getColumn(String columnkey)
    {
	LinkedList<IColumn> columnlist;
	if ((columnlist = this.columnstreemap.get(columnkey)) == null)
	{
	    return null;
	}
	return columnlist.getFirst();
    }

    @Override
    public Vector<IColumn> getAllColumns()
    {
	Collection<LinkedList<IColumn>> c = this.columnstreemap.values();
	Iterator<LinkedList<IColumn>> itr = c.iterator();
	Vector<IColumn> columns = new Vector<IColumn>(c.size(), 0);
	while (itr.hasNext())
	{
	    columns.add(itr.next().getFirst());
	}
	return columns;
    }

    @Override
    public boolean deleteColumn(String columnkey)
    {
	return (this.columnstreemap.remove(columnkey) != null);
    }

    // key does not need to be a newly created string. It is done in the method.
    private void createListAndAddColumn(IColumn column)
    {
	// TODO usare ID invece di nomecolonna?
	LinkedList<IColumn> entry_list = new LinkedList<IColumn>(); // TODO scegliere incremento e verificare quando viene attuato
	entry_list.addFirst(column); // add the first element to this new vector object ordered by timestamp
	this.columnstreemap.put(column.getName(), entry_list);
    }

    private void addFresherColumn(IColumn column, LinkedList<IColumn> entry_list)
    {
	entry_list.addFirst(column); // add the first element to this new vector object ordered by timestamp
    }

    /*
     * private TreeMap <String, Column> columnstreemap;
     * 
     * public ColumnsTreeMap() { this.columnstreemap = new TreeMap <String, Column>();
     * 
     * }
     */
}
